package com.b2c.erp.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.b2c.erp.DataConfigObject;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        Cookie[] cookies = request.getCookies();
        String token = null;
        if(cookies!=null){
            for (var c:cookies) {
                String cn = c.getName();
                if(cn.equals("token")){
                    token = c.getValue();
                }
            }
        }
        //System.out.println("Cookie值"+token);
        //HttpSession session = request.getSession();

//        HttpSession session = SessionHelper.getSession(request);
        /**当前访问的页面*/
        String targetUrl = request.getRequestURL().toString();
        if (StringUtils.isEmpty(request.getQueryString()) == false) {
            targetUrl += "?" + request.getQueryString();
        }

        //判断是否登录
        if(StringUtils.hasText(token)==false){
            //没有token，重新登录
            response.sendRedirect(request.getContextPath() + "/login?ref=" + URLEncoder.encode(targetUrl));
            return false;
        }else{
            //验证token是否正确
            String secret = DataConfigObject.getInstance().getJwtSecret();
            Algorithm algorithm = Algorithm.HMAC256(secret);
            try {
                JWTVerifier verifier = JWT.require(algorithm).withIssuer("auth0").build();

                DecodedJWT jwt = verifier.verify(token);
                Integer userId = jwt.getClaim("userId").asInt();
                String nickName = jwt.getClaim("userName").asString();
                return true;
            }catch (TokenExpiredException e){
                //token验证失败
//                Cookie c = new Cookie("token","");
//                response.addCookie(c);
                response.sendRedirect(request.getContextPath() + "/login?ref=" + URLEncoder.encode(targetUrl));
                return false;
//                throw new RuntimeException("401");
            }catch (Exception e){
//                Cookie c = new Cookie("token","");
//                response.addCookie(c);
                response.sendRedirect(request.getContextPath() + "/login?ref=" + URLEncoder.encode(targetUrl));
                return false;
            }
        }


//        if (StringUtils.isEmpty(session.getAttribute("userId"))) {
//            response.sendRedirect(request.getContextPath() + "/login?ref=" + URLEncoder.encode(targetUrl));
////            response.sendRedirect(request.getContextPath() + "/login");
//            return false;
//        } else {
////            session.setAttribute("userId", session.getAttribute("userId"));
//            return true;
//        }
    }
}
